package com.huxin.servelt;

import com.alibaba.fastjson.JSON;
import com.huxin.pojo.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/getCookie")
public class GetCookieServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        System.out.println("正在获取cookie");

        UserInfo userInfo=new UserInfo();
        //拿到请求头中的用户名密码
        Cookie[] cookies = req.getCookies();
        for (Cookie c : cookies) {
            if ("username".equals(c.getName())){
                userInfo.setUsername(c.getValue());
            } else if ("password".equals(c.getName())) {
                userInfo.setPassword(c.getValue());
            } else if ("jizhuwo".equals(c.getName())) {
                userInfo.setJizhuwo(c.getValue());
            }
        }
        //将user对象转为json字符串响应回前端
        String jsonString = JSON.toJSONString(userInfo);
        System.out.println(jsonString);
        resp.getWriter().write(jsonString);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
